package loader
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;

	public class DataLoader extends AbstractLoader
	{
		
		protected var _loader:URLLoader;
		
		public function DataLoader()
		{
			super();
		}
		
		public override function startLoad( url:String, desc:String, onProgress:Function, onCompleted:Function, onError:Function = null ):void
		{
			
			
			super.startLoad( url, desc, onProgress, onCompleted, onError );
			
			_loader = new URLLoader();
			
			_loader.addEventListener( Event.COMPLETE, completed );
			
			_loader.addEventListener( ProgressEvent.PROGRESS, progress );
			
			_loader.addEventListener( IOErrorEvent.IO_ERROR, error );
			
			_loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, error );
			
			_loader.data = URLLoaderDataFormat.BINARY;
			
			var request:URLRequest = new URLRequest( url );
			
			_loader.load( request );
			
			
		}
		
		protected function progress( evnet:ProgressEvent ):void
		{	
			super.onProgress( _loader.bytesLoaded, _loader.bytesTotal );
		}
		
		protected function completed( event:Event ):void
		{
			_loader.data = event.target.data;
			removeListener();
			super.onCompleted();
		}
		
		protected function error( event:Event ):void
		{	
			var errorTxt = "";
			
			if( event is IOErrorEvent )
			{
				errorTxt = IOErrorEvent( event ).text;
			}
			else if( event is SecurityErrorEvent )
			{
				errorTxt = SecurityErrorEvent( event ).text;
			}
			
			removeListener();
			
			super.onError( errorTxt );
		}
		
		public override function get content():Object
		{
			return _loader.data;
		}
		
		protected function removeListener():void
		{
			_loader.removeEventListener( Event.COMPLETE, completed );
			_loader.removeEventListener( ProgressEvent.PROGRESS, progress );
			_loader.removeEventListener( IOErrorEvent.IO_ERROR, error );
			_loader.removeEventListener( SecurityErrorEvent.SECURITY_ERROR, error );
		}
	
	}
	
}